package com.android.phoenix.activity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.phoenix.MainApplication;
import com.android.phoenix.R;
import com.android.phoenix.activity.location.SportCycleActivity;
import com.android.phoenix.activity.location.SportLocationActivity;
import com.android.phoenix.bluetooth.BicycleData;
import com.android.phoenix.bluetooth.BluetoothConnectActivity;
import com.android.phoenix.bluetooth.BluetoothService;
import com.android.phoenix.models.SportRecord;
import com.jjoe64.graphview.DefaultLabelFormatter;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;

/**
 * @ClassName: SportActivity
 * @Description: 运动页面
 * @author: SportActivity
 * @date: 2015-1-27 下午9:21:10
 */
public class SportActivity extends BaseActivity implements OnClickListener {

	private ImageView imgDeviceConnect;
	private Button btnSportCycle;
	private Button btnSportNavi;
	private TextView txt_totalsteps;
	private TextView txt_totaldistance;
	private TextView txt_totalcalorie;
	private GraphView graphView;
	private Boolean isBlutoothEnable = true;
	private BluetoothAdapter mBluetoothAdapter;
	private int REQUEST_ENABLE_BT = 0;
	private BicycleData mBicycleData;
	private boolean isBeyong1W = false;

	private List<SportRecord> listRecord = new ArrayList<SportRecord>();
	private List<SportRecord> listLastRecord = new ArrayList<SportRecord>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acti_sport);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		initView();
		IntentFilter filter = new IntentFilter(
				BluetoothService.ACTION_CMD_RECEIVE);
		registerReceiver(mReceiver, filter);
	}

	/**
	 * @Title: initViews
	 * @Description: 控件等初始化
	 * @author: WanChao
	 * @date: 2015-1-16 下午11:59:31
	 */
	private void initView() {
		imgDeviceConnect = (ImageView) findViewById(R.id.imgDeviceConnect);
		btnSportCycle = (Button) findViewById(R.id.btnSportCycle);
		btnSportNavi = (Button) findViewById(R.id.btnSportNavi);
		btnSportCycle.setOnClickListener(this);
		btnSportNavi.setOnClickListener(this);
		imgDeviceConnect.setOnClickListener(this);

		txt_totalsteps = (TextView) this.findViewById(R.id.txt_totalsteps);
		txt_totaldistance = (TextView) this
				.findViewById(R.id.txt_totaldistance);
		txt_totalcalorie = (TextView) this.findViewById(R.id.txt_totalcalorie);
		graphView = (GraphView) this.findViewById(R.id.graph_view);
		getDateFromDB();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	/**
	 * 
	 * @Title: initGraphView
	 * @Description: TODO(图形)
	 * @author: wanglei
	 * @date: 2015-1-29 上午11:16:48
	 */
	private void initGraphView() {
		BarGraphSeries<DataPoint> series = new BarGraphSeries<DataPoint>();
		float oneTotaldistance = 0;
		float MaxDistance = 0;
		for (int i = 0; i < listLastRecord.size(); i++) {
			series.appendData(
					new DataPoint(new Date(Long.parseLong(listLastRecord.get(i)
							.getStartTime())).getHours(), Double
							.parseDouble(listLastRecord.get(i).getDistance())),
					true, 24);
			if (MaxDistance <= Float.parseFloat(listLastRecord.get(i)
					.getDistance())) {
				MaxDistance = Float.parseFloat(listLastRecord.get(i)
						.getDistance());
			}

			oneTotaldistance += MaxDistance;
			if (oneTotaldistance > 10) {
				isBeyong1W = true;
			}
		}
		if (listLastRecord.size() < 4) {
			for (int i = 0; i < 4 - listLastRecord.size(); i++) {
				series.appendData(new DataPoint(24d, 0d), true, 24);
			}
		} else {
			// draw values on top
			series.setDrawValuesOnTop(true);
			series.setValuesOnTopColor(Color.WHITE);
			series.setValuesOnTopSize(15);
			series.setColor(Color.BLUE);
		}
		setGraphViewPara(series);
		if (isBeyong1W) {
			graphView.setTitle(listLastRecord.get(0).getDate() + "运动了"
					+ oneTotaldistance * 1000 + "米，要加油哦");
		} else {
			graphView.setTitle(listLastRecord.get(0).getDate() + "运动了"
					+ oneTotaldistance * 1000 + "米，继续加油加油哦");
		}

		graphView.setTitleColor(Color.WHITE);
		graphView.getViewport().setMaxY((int) (MaxDistance + 1));
		graphView.getViewport().setMinY(0);
		graphView.getViewport().setYAxisBoundsManual(true);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent it = null;
		switch (v.getId()) {
		case R.id.btnSportCycle:
			it = new Intent(SportActivity.this, SportCycleActivity.class);
			startActivity(it);

			break;

		case R.id.btnSportNavi:
			it = new Intent(SportActivity.this, SportLocationActivity.class);
			startActivity(it);
			break;
		case R.id.imgDeviceConnect: {
			if (!getPackageManager().hasSystemFeature(
					PackageManager.FEATURE_BLUETOOTH)) {
				Toast.makeText(this,
						getResources().getString(R.string.blu_not_supported),
						Toast.LENGTH_SHORT).show();
			}
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			if (!mBluetoothAdapter.isEnabled()) {
				isBlutoothEnable = false;
				Intent enableBtIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			}
			if (isBlutoothEnable) {
				it = new Intent(SportActivity.this,
						BluetoothConnectActivity.class);
				startActivity(it);
				finish();
			}
			break;
		}
		}

	}

	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(BluetoothService.ACTION_CMD_RECEIVE)) {
				byte[] data = intent
						.getByteArrayExtra(BluetoothService.MSGTOAST);
				mBicycleData = new BicycleData(data);
				if (mBicycleData.isHRMeasureStart)
					updateUI();
			}
		}
	};

	private void updateUI() {

	}

	private void getDateFromDB() {
		try {
			listRecord = MainApplication.getDataHelper(SportActivity.this)
					.getSportRecordDao().queryForAll();
			if (listRecord == null || listRecord.size() < 1) {
				initTestGraphView();
				return;
			}
			listLastRecord = MainApplication
					.getDataHelper(SportActivity.this)
					.getSportRecordDao()
					.queryForEq("date",
							listRecord.get(listRecord.size() - 1).getDate());

		} catch (SQLException e) {
			e.printStackTrace();
		}
		int totalsteps = 0;
		float totalcalorie = 0;
		float totaldistance = 0;
		for (int i = 0; i < listRecord.size(); i++) {
			totaldistance += Float.parseFloat(listRecord.get(i).getDistance());
			totalsteps += (int) (totaldistance * 1000 / 1.8f);
			totalcalorie += Float.parseFloat(listRecord.get(i).getCalorie());
		}
		txt_totalcalorie.setText(totalcalorie + "");
		txt_totaldistance.setText(totaldistance + "");
		txt_totalsteps.setText(totalsteps + "");

		initGraphView();
	}

	/**
	 * 
	 * @Title: initGraphView
	 * @Description: TODO(图形)
	 * @author: wanglei
	 * @date: 2015-1-29 上午11:16:48
	 */
	private void initTestGraphView() {
		BarGraphSeries<DataPoint> series = new BarGraphSeries<DataPoint>();

		// draw values on top
		series.setDrawValuesOnTop(true);
		series.setValuesOnTopColor(Color.WHITE);
		series.setValuesOnTopSize(15);
		series.setColor(Color.BLUE);
		// 数据必须大于一个点，要不然报空指针 最多24个点
		// 格式： 前一个参数是时间点（横坐标），后一个参数是具体数值（纵坐标），
		series.appendData(new DataPoint(9, 6.7d), true, 24);
		series.appendData(new DataPoint(13, 4.2d), true, 24);
		series.appendData(new DataPoint(16, 8.653d), true, 24);
		series.appendData(new DataPoint(20, 5.2d), true, 24);
		setGraphViewPara(series);

		graphView.setTitle("运动情况");
		graphView.setTitleColor(Color.WHITE);

	}

	private void setGraphViewPara(BarGraphSeries<DataPoint> series) {
		series.setSpacing(75);

		// 设置x,Y最大最小值
		graphView.getViewport().setMinX(0);
		graphView.getViewport().setMaxX(24);
		graphView.getViewport().setMaxY(10);
		graphView.getViewport().setMinY(0);
		graphView.getViewport().setYAxisBoundsManual(true);
		graphView.getViewport().setXAxisBoundsManual(true);

		// 设置横纵坐标单位
		// custom label formatter to show currency "EUR"
		graphView.getGridLabelRenderer().setLabelFormatter(
				new DefaultLabelFormatter() {
					@Override
					public String formatLabel(double value, boolean isValueX) {
						if (isValueX) {
							// show normal x values
							return super.formatLabel(value, isValueX) + "h";
						} else {
							// show currency for y values
							return super.formatLabel(value, isValueX) + "KM";
						}
					}
				});
		graphView.getGridLabelRenderer().setHorizontalLabelsColor(Color.WHITE);
		graphView.getGridLabelRenderer().setVerticalLabelsColor(Color.WHITE);
		graphView.addSeries(series);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (REQUEST_ENABLE_BT == requestCode && RESULT_OK == resultCode)
			isBlutoothEnable = true;
	}
}
